//
//  LGAuthorization.m
//  微博oc版
//
//  Created by Apple_Lzzy27 on 16/10/14.
//  Copyright © 2016年 Apple_Lzzy27. All rights reserved.
//

#import "LGAuthorization.h"
@interface LGAuthorization()<UIWebViewDelegate>

@property(nonatomic,weak) UIWebView *webView;

@end
@implementation LGAuthorization


- (void)loadView{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.webView = webView;
    self.view = webView;
    
}
- (void)viewDidLoad{
    [super viewDidLoad];
    self.webView.delegate = self;
    
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonCustButton:@"返回" fontSize:14 addTarget:self action:@selector(back) isBack:YES];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonCustButton:@"自动填充" fontSize:14 addTarget:self action:@selector(autofull) isBack:NO];
    //client_id	true	string	申请应用时分配的AppKey
    //AppKey 3949464217
    NSURL *url=[NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=800817303&response_type=code&redirect_uri=http://52it.me"];
    
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];

}

- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)autofull{
    
    //调用javaScript
    NSString *javaScript = @"document.getElementById('userId').value='15677283050';document.getElementById('passwd').value='m1579116334';";
    //自动注入
    [self.webView stringByEvaluatingJavaScriptFromString:javaScript];
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlString = request.URL.absoluteString;

    
    if ([urlString hasPrefix:@"http://52it.me"] == false) {
        return YES;
    }
    NSString *url = request.URL.query;

    if ([url hasPrefix:@"code="] == false) {
        NSLog(@"授权失败");
        return false;
    }
    NSLog(@"%@",url);
    
    //截取字符串
    NSString *suCode = @"code=";
    
    
    NSInteger index = [url rangeOfString:suCode].length;
    
    NSString *code = [url substringFromIndex:index];
    
    //拿到code，发送请求，获取token
    [[LGNetWorkingManager manager] loadTokenRequest:code completion:^(bool isSuccess) {
         NSLog(@"授权成功");
    }];
   
    
    
    return NO;
}










@end
